<?php

class VKontakteService extends Auth
{
    public $clientId='';
    public $clientSecret='';
    protected $token='', $userId='';
    protected $userInfo=false, $serviceName='vkontakte';

    public function getUserInfo()
    {
        $info=$this->userInfo;
        return array(
            'user'=>array(
                'login'=>isset($info->uid) ? $info->uid : '',
                'userName'=>isset($info->uid) ? $info->uid : '',
                'password'=>'',
                'confirmCode'=>'',
                'email'=>isset($info->email) ? $info->email : '',
                'isConfirmed'=>1,
                'isActive'=>1,
            ),
            'profile'=>array(
                'firstName'=>isset($info->first_name) ? $info->first_name : '',
                'lastName'=>isset($info->last_name) ? $info->last_name : '',
                'patronymic'=>isset($info->nickname) ? $info->nickname : '',
                'sex'=>$info->sex!=2 ? 1 : 0,
                'img'=>isset($info->photo) ? $info->photo : '',
                'birthday'=>isset($info->bdate) ? $info->bdate : '',
            ),
        );
    }

    public function getToken()
    {
        return $this->token;
    }

    public function getServiceName()
    {
        return $this->serviceName;
    }

    public function firstRequest()
    {
        $redirectUrl='http://oauth.vk.com/authorize?client_id='.$this->clientId.
            '&redirect_uri='.$this->getReturnUrl().
            '/&response_type=code';

        Yii::app()->request->redirect($redirectUrl);
    }

    public function secondRequest()
    {
        if($code=Yii::app()->request->getQuery('code')){
            $redirectUrl='https://oauth.vk.com/access_token?client_id='.$this->clientId.
                '&client_secret='.$this->clientSecret.
                '&code='.$code.
                '&redirect_uri='.$this->getReturnUrl().'/';

            if($request=json_decode(file_get_contents(str_replace('amp;','',$redirectUrl)))){
                $this->token=$request->access_token;
                $this->userId=$request->user_id;

                $redirectUrl='https://api.vk.com/method/users.get?uids='.$this->userId.
                '&fields=uid,first_name,last_name,nickname,screen_name,sex,bdate,city,country,timezone,photo'.
                '&access_token='.$this->token;

                if($this->token && $this->userId && is_object($request=json_decode(file_get_contents($redirectUrl)))){
                    $this->userInfo=$request->response[0];
                    return true;
                }
            }
        }

        return false;
    }
}